# coding:utf-8
import configparser
import json
import os
import requests
import re

import sys


class Renren:
    def __init__(self):
        self.post_url = 'http://www.renren.com/PLogin.do'
        self.rkey_url = 'http://login.renren.com/ajax/getEncryptKey'
        self.url = 'http://www.renren.com/960768847'
        self.filename = 'ext/E8_renren_session.html'
        self.post_data = {
            'email': '',
            'icode': '',
            'origURL': 'http://www.renren.com/home',
            'domain': 'renren.com',
            'key_id': '1',
            'captcha_type': 'web_login',
            'password': '',
            'rkey': '',
            'f': 'http%3A%2F%2Fzhibo.renren.com%2Ftop'
        }
        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}

    def run(self):
        _user_pswd_cfg = os.environ['user_pswd']
        _cf = configparser.ConfigParser()
        _cf.read(_user_pswd_cfg)
        self.post_data['email'] = _cf.get('renren', 'renren_user')
        self.post_data['password'] = _cf.get('renren', 'renren_pswd')
        _user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)
        _s = requests.session()
        self.post_data['rkey'] = json.loads(_s.get(self.rkey_url, headers=_user_agent).content.decode())['rkey']
        print(self.post_data)
        # TODO 密码js解析、二维码解析
        # _response = _s.post(self.post_url, data=self.post_data, headers=_user_agent)
        # print(_response.url)
        # _response = _s.get(self.url)
        # print(_response.url)
        # _html = _response.content.decode()
        # if re.findall(r'李震', _html):
        #     with open(self.filename, mode='w', encoding='utf-8')as f:
        #         f.write(_html)
        # else:
        #     print('not found!')


def main():
    rr = Renren()
    rr.run()


if __name__ == '__main__':
    main()
